﻿#region

using System.Collections;
using System.ComponentModel.DataAnnotations;

#endregion

namespace Vin.Tool.Attributes.Validation;

/// <summary>
/// 只能使用List<string> 接收参数
/// </summary>
public class StringArrayAttribute : ValidationAttribute
{
    /// <summary>
    /// 分隔符
    /// </summary>
    public string Separator { get; set; } = ",";

    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
    {
        if (value == null || value is not IList tempList) return new ValidationResult(ErrorMessage);
        if (tempList.Count >= 1)
        {
            var list = new List<string>();
            foreach (var item in tempList)
            {
                if (item == null) continue;
                var arr = item.ToString()?.Split(Separator)!;
                foreach (var s in arr)
                {
                    if (string.IsNullOrEmpty(s)) continue;
                    list.Add(s);
                }
            }

            var displayObj = validationContext.ObjectType.GetProperty(validationContext.DisplayName);
            if (displayObj != null)
            {
                displayObj.SetValue(validationContext.ObjectInstance, list);
            }
            else
            {
                tempList.Clear();
                foreach (var item in list)
                {
                    tempList.Add(item);
                }
            }
        }

        return ValidationResult.Success;
    }
}